package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.CollectionUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.AttachPopupView;
import com.lxj.xpopup.enums.PopupPosition;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.stark.apkextract.lib.model.AeExporter;
import com.stark.apkextract.lib.model.AeUtil;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.AppAdapter;
import flc.ast.bean.ApkBean;
import flc.ast.databinding.ActivityApkManageBinding;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.base.GeneralEvtDialog;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.IntentUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;

public class ApkManageActivity extends BaseAc<ActivityApkManageBinding> {

    private AppAdapter appAdapter;
    private boolean isEdit = false;
    private int selPosition;
    private AttachPopupView attachPopupView;

    @Override
    protected int onCreate() {
        return R.layout.activity_apk_manage;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivApkManageBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.rvApkList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        appAdapter = new AppAdapter();
        mDataBinding.rvApkList.setAdapter(appAdapter);
        appAdapter.addChildClickViewIds(R.id.ivAppItemEdit);
        appAdapter.setOnItemChildClickListener(this);
        mDataBinding.ivApkManageRecord.setOnClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivApkManageRecord://导出记录
                startActivity(ExportRecordActivity.class);
                break;
        }
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        selPosition = position;
        switch (view.getId()) {
            case R.id.ivAppItemEdit:
                attachPopupView = new XPopup.Builder(mContext)
                        .hasShadowBg(false)
//                            .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
//                        .isDarkTheme(true)
//                        .popupAnimation(PopupAnimation.NoAnimation) //NoAnimation表示禁用动画
//                        .isCenterHorizontal(true) //是否与目标水平居中对齐
//                        .offsetY(-60)
//                        .offsetX(80)
                        .popupPosition(PopupPosition.Left) //手动指定弹窗的位置
                        .atView(view)  // 依附于所点击的View，内部会自动判断在上方或者下方显示
                        .asAttachList(new String[]{getString(R.string.export), getString(R.string.share)},
                                new int[]{R.drawable.adaochu, R.drawable.afenx},
                                new OnSelectListener() {
                                    @Override
                                    public void onSelect(int position, String text) {
                                        switch (position) {
                                            case 0:
                                                getPermission();
                                                break;
                                            case 1:
                                                IntentUtil.shareFile(mContext, (AppUtils.getAppPath(appAdapter.getItem(position).pkgName)));
                                                break;
                                        }
                                    }
                                }, 0, 0);
                ;
//                }
                attachPopupView.show();
                break;
        }
    }

    @Override
    protected void initData() {
        loadApks();
    }

    private void loadApks() {
        showDialog(getString(com.stark.common.res.R.string.loading));
        RxUtil.create(new RxUtil.Callback<List<String>>() {
            @Override
            public void doBackground(ObservableEmitter<List<String>> emitter) {
                emitter.onNext(AeUtil.getNoSystemInstalledPackageNames());
            }

            @Override
            public void accept(List<String> packageNames) {
                if (!CollectionUtils.isEmpty(packageNames)) {
                    mDataBinding.rvApkList.setVisibility(View.VISIBLE);
                    mDataBinding.ivApkManageNoData.setVisibility(View.GONE);
                    List<ApkBean> apkBeans = new ArrayList<>();
                    ApkBean bean;
                    for (String packageName : packageNames) {
                        bean = new ApkBean();
                        bean.pkgName = packageName;
                        apkBeans.add(bean);
                    }
                    appAdapter.setList(apkBeans);
                } else {
                    mDataBinding.rvApkList.setVisibility(View.GONE);
                    mDataBinding.ivApkManageNoData.setVisibility(View.VISIBLE);
                }
                dismissDialog(500L);
            }
        });
    }

    //获取权限
    private void getPermission() {
        StkPermissionHelper.reqManageExternalStoragePermission()
                .reqPermissionDesc(getString(R.string.get_app_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        exportAfter();
                    }
                })
                .request();
    }

    private void exportAfter() {
        String packageName = appAdapter.getItem(selPosition).pkgName;
        AeExporter.getInstance().export(packageName);
        boolean isExist = AeExporter.getInstance().isExportExist(packageName);
        if (isExist) {
            //已存在
            String apkFileName = AeExporter.getExportFileName(packageName);
            String exportRootDir = AeExporter.getExportRootDir();
            String content = getString(R.string.ae_apk_exist_tip_fmt, apkFileName, exportRootDir);
            new GeneralEvtDialog.Builder(this)
                    .title(getString(com.stark.common.res.R.string.prompt))
                    .content(content)
                    .leftBtnText(getString(com.stark.common.res.R.string.cover))
                    .leftBtnListener(v -> {
                        startExport(packageName);
                    })
                    .rightBtnText(getString(com.stark.common.res.R.string.no_cover))
                    .rightBtnTextColor(Color.parseColor("#0000FF"))
                    .build()
                    .show();
            return;
        }

        //不存在
        String appName = AppUtils.getAppName(packageName);
        String exportRootDir = AeExporter.getExportRootDir();
        String content = getString(R.string.ae_apk_not_exist_tip_fmt, appName, exportRootDir);
        new GeneralEvtDialog.Builder(this)
                .title(getString(com.stark.common.res.R.string.prompt))
                .content(content)
                .rightBtnListener(v -> {
                    startExport(packageName);
                })
                .rightBtnTextColor(Color.parseColor("#0000FF"))
                .build()
                .show();
    }

    private void startExport(String packageName) {
        showDialog(getString(com.stark.common.res.R.string.exporting));
        RxUtil.create(new RxUtil.Callback<Boolean>() {
            @Override
            public void doBackground(ObservableEmitter<Boolean> emitter) {
                emitter.onNext(AeExporter.getInstance().export(packageName));
            }

            @Override
            public void accept(Boolean success) {
                dismissDialog();
                if (success != null && success) {
                    ToastUtils.showShort(getString(com.stark.common.res.R.string.export_success));
                } else {
                    ToastUtils.showShort(getString(com.stark.common.res.R.string.export_failure));
                }
            }
        });
    }

}